package com.gzhryc.shared_device.oem.code.agent.services;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.jdbc.Conditions;
import com.gzhryc.jdbc.JdbcSession;
import com.gzhryc.jdbc.MultiDBTools;
import com.gzhryc.shared_device.oem.code.agent.dao.AgentRelationDeviceDao;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentRelationDevice;
import com.gzhryc.shared_device.oem.code.agent.dao.models.RelationUserDeviceCount;
import com.gzhryc.shared_device.oem.code.agent.services.dto.AgentRelationDeviceSearch;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

public class AgentRelationDeviceService {

    static Logger log = Logger.getLogger(AgentRelationDeviceService.class);

    public static AgentRelationDeviceService self() {
        return MultiDBTools.getService(AgentRelationDeviceService.class, true);
    }

    public static AgentRelationDeviceService self(String jdbcKey) {
        return MultiDBTools.getService(jdbcKey, AgentRelationDeviceService.class, true);
    }

    AgentRelationDeviceDao dao;

    public AgentRelationDeviceService(String jdbcKey) {
        this.dao = new AgentRelationDeviceDao(jdbcKey);
    }

    public List<AgentRelationDevice> findJoinBySearch(AgentRelationDeviceSearch search,Integer pageNo,Integer pageLimit){
        Conditions conditions = dao.buildConditions(search);
        conditions.and().is("device.state",search.getState());
        conditions.and().in("device.device_type_id",search.getDeviceTypeIds());
        if(search.getDeploy() != null){
            if(search.getDeploy()){
                conditions.and().isNotNull("device.place_id");
            }else{
                conditions.and().isNull("device.place_id");
            }
        }
        try {
            return dao.findJoinByCondition(conditions,pageNo,pageLimit);
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    public Long countJoinBySearch(AgentRelationDeviceSearch search) {
        Conditions conditions = dao.buildConditions(search);
        conditions.and().is("device.state",search.getState());
        conditions.and().in("device.device_type_id",search.getDeviceTypeIds());
        if(search.getDeploy() != null){
            if(search.getDeploy()){
                conditions.and().isNotNull("device.place_id");
            }else{
                conditions.and().isNull("device.place_id");
            }
        }

        try {
            return dao.countJoin(conditions);
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
        }
        return 0L;
    }

    public List<AgentRelationDevice> findJoinByUserKeys(Long userId, Long relationUserId){
        if(userId != null && relationUserId != null){
            Conditions conditions = new Conditions(AgentRelationDevice.class);
            conditions.and().is("userId", userId);
            conditions.and().is("relationUserId", relationUserId);

            try {
                return dao.findJoinByCondition(conditions);
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return null;
    }

    public List<String> findDeviceSnBySearch(AgentRelationDeviceSearch search){
        Conditions conditions = dao.buildConditions(search);
        conditions.and().is("device.state",search.getState());
        conditions.and().in("device.device_type_id",search.getDeviceTypeIds());
        conditions.and().likeBoth("deviceSn",search.getTrim()).or().likeBoth("device.placeName",search.getTrim());
        if(search.getDeploy() != null){
            if(search.getDeploy()){
                conditions.and().isNotNull("device.place_id");
            }else{
                conditions.and().isNull("device.place_id");
            }
        }

        try {
            return dao.findDeviceSn(conditions);
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }

    public List<RelationUserDeviceCount> findDeviceCountByUserKeys(Long userId,List<Long> relationUserIds){
        if(userId != null && relationUserIds != null && relationUserIds.size() > 0){
            Conditions conditions = new Conditions(AgentRelationDevice.class);
            conditions.and().is("userId",userId);
            conditions.and().in("relationUserId",relationUserIds);

            try {
                return dao.countGroupRelationUserId(conditions);
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return null;
    }

    public AgentRelationDevice getByKeys(Long userId,Long relationUserId,String deviceSn){
        if(userId != null && relationUserId != null && StringTools.isNotBlank(deviceSn)) {
            Conditions conditions = new Conditions(AgentRelationDevice.class);
            conditions.and().is("userId", userId);
            conditions.and().is("relationUserId", relationUserId);
            conditions.and().is("deviceSn", deviceSn);

            try {
                return dao.get(conditions);
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        }
        return null;
    }

    public AgentRelationDevice getJoinByKeys(Long userId,Long relationUserId,String deviceSn){
        if(userId != null && relationUserId != null && StringTools.isNotBlank(deviceSn)) {
            Conditions conditions = new Conditions(AgentRelationDevice.class);
            conditions.and().is("userId", userId);
            conditions.and().is("relationUserId", relationUserId);
            conditions.and().is("deviceSn", deviceSn);

            try {
                return dao.getJoin(conditions);
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        }
        return null;
    }
    
    public List<AgentRelationDevice> findBykeys(Long userId,Long relationUserId,List<String> deviceSnList){
    	if(userId != null && relationUserId != null && deviceSnList != null && deviceSnList.size() > 0) {
            Conditions conditions = new Conditions(AgentRelationDevice.class);
            conditions.and().is("userId", userId);
            conditions.and().is("relationUserId", relationUserId);
            conditions.and().in("deviceSn", deviceSnList);

            try {
                return dao.findByCondition(conditions);
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        }
    	return null;
    }
    
    public boolean add(List<AgentRelationDevice> agentRelationDeviceList) throws LogicException{
    	JdbcSession.begin();
    	try {
            int total = dao.insert(agentRelationDeviceList);
            if(total == agentRelationDeviceList.size()) {
            	JdbcSession.commit();
            	return true;
            }
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }finally {
        	JdbcSession.end();
        }
    	return false;
    }

    public boolean add(AgentRelationDevice agentRelationDevice) throws LogicException {
        AgentRelationDevice temp = getByKeys(agentRelationDevice.getUserId(),agentRelationDevice.getRelationUserId(),agentRelationDevice.getDeviceSn());
        if(temp != null){
            throw new LogicException("用户已分派了该设备");
        }
        agentRelationDevice.setCreateDate(new Date());
        try {
            return dao.insert(agentRelationDevice) > 0;
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return false;
    }

    public boolean deleteByUsers(Long userId,Long relationUserId){
        if(userId != null && relationUserId != null) {
            Conditions conditions = new Conditions(AgentRelationDevice.class);
            conditions.and().is("userId", userId);
            conditions.and().is("relationUserId", relationUserId);

            try {
                return dao.deleteByCondition(conditions) >= 0;
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        }
        return false;
    }
}
